import React, { memo, useEffect } from 'react';
import { shallowEqual, useDispatch, useSelector } from 'react-redux';

import { getRankingRequest, changeCurrentIndex } from "../../store/actionCreators";
import { formatImageSize } from "@/utils/format-utils";

import { TabsWrapper } from "./style";


const RankingTabs = memo(() => {
  // redux
  const dispatch = useDispatch();
  const { tabList, currentIndex } = useSelector(state => ({
    tabList: state.getIn(["ranking", "tabList"]),
    currentIndex: state.getIn(["ranking", "currentIndex"])
  }), shallowEqual);
  
  // hooks
  useEffect(() => {
    const id = tabList[currentIndex] && tabList[currentIndex].id;
    if (!id) return;
    dispatch(getRankingRequest(id))
  }, [dispatch, tabList, currentIndex]);

  // handle function
  const addClassName = (index) => {
    let claN = "item";
    if (index === currentIndex) {
      claN += " active";
    };
    return claN;
  };

  const handlerItemClick = (index) => {
    dispatch(changeCurrentIndex(index))
  };

  return (
    <TabsWrapper>
      {
        tabList.map((item, index) => {
          let header;
          if (index === 0 || index === 4) {
            header = <div className="header">{ index === 0 ? "云音乐特色榜" : "全球媒体榜" }</div>
          };

          return (
            <div key={item.id}>
              { header }

              <div 
                className={addClassName(index)}
                onClick={e => handlerItemClick(index)}  
              >
                <img src={formatImageSize(item.coverImgUrl, 40)} alt="" />

                <div className="info">
                  <div className="name">{ item.name }</div>
                  <div className="update">{ item.updateFrequency }</div>
                </div>
              </div>
            </div>
          )
        })
      }
    </TabsWrapper>
  )
})

export default RankingTabs